package tools

import (
    "encoding/base64"
    "io"
    "log"
    "net/http"
    "net/url"
    "os"
    "path"
    "regexp"
    "strings"
)

func TrimBase64Header(encoded string) string {
    r := regexp.MustCompile(`^data:image/.*?,`)
    encoded = strings.TrimSpace(encoded)
    //encoded = strings.TrimSuffix(encoded, "=")
    return r.ReplaceAllString(encoded, "")
}

func Base64ToFile(base64String string, filename string) error {
    b, err := base64.StdEncoding.DecodeString(base64String)
    if err != nil {
        log.Println(err.Error())
        return err
    }
    out, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer out.Close()

    _, err = out.Write(b)
    return err
}

func GetDownloadFilename(resp *http.Response, url *url.URL) string {
    contentDisposition := resp.Header.Get("Content-Disposition")
    if contentDisposition != "" {
        // Extract the filename from Content-Disposition header if present
        cdSplit := strings.Split(contentDisposition, ";")
        for _, part := range cdSplit {
            if strings.Contains(part, "filename") {
                filenameParts := strings.Split(part, "=")
                if len(filenameParts) > 1 {
                    return strings.Trim(filenameParts[1], "\"")
                }
            }
        }
    }

    // Fallback to the segment after the last slash in the path
    return path.Base(url.Path)
}

func Copy(src string, dst string) error {

    fin, err := os.Open(src)
    if err != nil {
        log.Println(err)
    }
    defer fin.Close()

    fout, err := os.Create(dst)
    if err != nil {
        log.Println(err)
    }
    defer fout.Close()

    _, err = io.Copy(fout, fin)

    if err != nil {
        log.Println(err)
    }
    return err
}
